package com.funong.matrix.biz.base.dao;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.funong.matrix.biz.base.entity.SysInmailEntity;
import com.funong.matrix.biz.base.entity.SysSendTaskEntity;
import com.funong.matrix.biz.base.entity.SysTagEntity;
import com.funong.matrix.biz.base.mapper.SysInmailMapper;
import com.funong.matrix.biz.base.mapper.SysTagMapper;
import com.funong.matrix.core.base.Dao;
import com.funong.matrix.core.base.FunongBaseDao;
import com.funong.matrix.core.dto.QueryDTO;
import com.funong.matrix.core.dto.Result;
import com.funong.matrix.core.utils.StringUtil;
import org.aspectj.lang.annotation.Aspect;

import java.util.List;

/**
 * @author : NaNa
 * @since : 2023-05-19 16:40
 **/
@Aspect
@Dao
public class SysInmailDao extends FunongBaseDao<SysInmailMapper, SysInmailEntity> {

    public void saveMessageEntity(SysSendTaskEntity sendTaskEntity){
        SysInmailEntity inmailEntity = new SysInmailEntity();

        inmailEntity.setTitle(sendTaskEntity.getTitle());
        inmailEntity.setContent(sendTaskEntity.getContent());
        String receivers = sendTaskEntity.getReceiver();
        List<String> receiverList = StringUtil.split(receivers);
        for (String receiverId : receiverList) {
            inmailEntity.setReceiver(receiverId);
            save(inmailEntity);
        }
    }

    public Result queryInmail(QueryDTO<SysInmailEntity> queryDTO) {
        ObjectMapper mapper = new ObjectMapper();
        SysInmailEntity inmailDTO = mapper.convertValue(queryDTO.getCondition(), SysInmailEntity.class);

        Page<SysInmailEntity> page = new Page<>(queryDTO.getPageNo(), queryDTO.getPageSize());
        IPage<SysInmailEntity> iPage = this.baseMapper.selectPage(page, Wrappers.<SysInmailEntity>lambdaQuery()
                .eq(!StringUtils.isEmpty(inmailDTO.getReceiver()), SysInmailEntity::getReceiver, inmailDTO.getReceiver())
                .eq(null != inmailDTO.getIsRead(), SysInmailEntity::getIsRead, inmailDTO.getIsRead())
        );
        return Result.page(iPage, iPage.getRecords());
    }


    public Result readInmail(List<Integer> idList) {
        int updateNum = 0;
        for (Integer read : idList) {
            SysInmailEntity inmailEntity = this.baseMapper.selectById(read);
            inmailEntity.setIsRead(1);
            updateNum += this.baseMapper.updateById(inmailEntity);
        }
        return Result.success(updateNum);
    }
}
